package logic

import (
	"context"
	"errors"
	"wx/cache"
	"wx/models/mysql"
	"wx/pkg"

	"wx/wxrpc/internal/svc"
	"wx/wxrpc/wxrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *wxrpc.RegisterRequest) (*wxrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this
	result, _ := cache.Rdb.Get(l.ctx, "captchaCode"+in.Mobile).Result()
	if result != in.SendCode {
		return nil, errors.New("短信验证码错误,请重新输入")
	}

	var findUser mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile)
	if in.Mobile == findUser.Mobile {
		return nil, errors.New("当前用户已注册")
	}

	user := mysql.User{
		Mobile:    in.Mobile,
		Password:  pkg.Md5str(in.Password),
		HeadImage: in.HeadImage,
		Address:   in.Address,
	}
	mysql.DB.Debug().Create(&user)

	return &wxrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
